package com.wondream.example.io.nio.socket.simple02;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author wangjun
 * @note NioClient
 * @date 2023-11-24  13:10
 */
public class NioClient {
    public static void main(String[] args) throws Exception {
        // 1.客户端socket通道
        SocketChannel socketChannel = SocketChannel.open();
        // 2.设置非阻塞
        socketChannel.configureBlocking(false);
        // 3.初始化服务端ip和端口号
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8888);
        // 4.连接服务端
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("Client：没连接上，干点别的事");
            }
        }
        // 5.把数据存到缓冲区
        String msg = "hello, server";
        ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
        // 6.发送数据
        socketChannel.write(byteBuffer);
        System.out.println(String.format("客户端发送了数据：%s", msg));
        // 7.关闭
//        socketChannel.close();
        System.in.read(); // 阻塞客户端
    }
}
